package org.wskyh.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Scanner;

public class UDPClient {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8866);

        // 发送消息
        new Thread(() -> {
            // 反复发送消息
            String request;
            Scanner scanner = new Scanner(System.in);
            try {
                InetAddress inetAddress = InetAddress.getByName("192.168.43.254");
                do {
                    request = scanner.next();
                    DatagramPacket packet = new DatagramPacket(request.getBytes(), request.getBytes().length, inetAddress, 8888);
                    socket.send(packet);
                } while (!"exit".equals(request));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // 接收信息
        new Thread(() -> {
            try {
                byte[] bytes;
                do {
                    bytes = new byte[1024];
                    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
                    socket.receive(packet);
                    System.out.println("服务端：" + new String(packet.getData()));
                } while (!"exit".equals(new String(Arrays.copyOf(bytes, 4))));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
